package bTree.LeetCode;

import java.util.ArrayList;
import java.util.List;

public class 螺旋矩阵 {
    public List<Integer> spiralOrder(int[][] matrix) {
        //定义结果数组
        List<Integer> res = new ArrayList<>();
        //拿到列和行
        int line = matrix.length;
        int row = matrix[0].length;
        //定义边界，进行模拟
        int left = 0, right = row, top = 0, bottom = line;
        while (left < right && top < bottom) {
            //从左向右
            for (int i = left; i < right; i++) {
                res.add(matrix[top][i]);
            }
            top++;
            if (top == bottom) {
                break;
            }

            //从上到下
            for (int i = top; i < bottom; i++) {
                res.add(matrix[i][right - 1]);
            }
            right--;
            if (left == right) {
                break;
            }

            //从右到左
            for (int i = right - 1; i >= left; i--) {
                res.add(matrix[bottom - 1][i]);
            }
            bottom--;
            if (top == bottom) {
                break;
            }

            //从下到上
            for (int i = bottom - 1; i >= top; i--) {
                res.add(matrix[i][left]);
            }
            left++;
            if (left == right) {
                break;
            }
        }
        return res;
    }
}